// 加载角色列表并渲染到表格，含操作按钮
function loadRoleList() {
  fetch('/api/admin/roles', {
    headers: {
      'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
    }
  })
    .then(res => res.json())
    .then(data => {
      const roleList = document.getElementById('roleList');
      if (!roleList) return;
      roleList.innerHTML = '';
      if (data.success && Array.isArray(data.data)) {
        data.data.forEach(role => {
          const tr = document.createElement('tr');
          tr.innerHTML = `
            <td>${role.name || ''}</td>
            <td>${role.description || ''}</td>
            <td>
              <button class="btn btn-sm btn-warning" onclick="editRole(${role.id})">编辑</button>
              <button class="btn btn-sm btn-danger" onclick="deleteRole(${role.id})">删除</button>
              <button class="btn btn-sm btn-info" onclick="viewRoleLog(${role.id})">日志</button>
            </td>
          `;
          roleList.appendChild(tr);
        });
      }
    })
    .catch(err => {
      console.error('加载角色列表失败:', err);
    });
}
// 角色管理页面JS
// 依赖：页面有id=createRoleBtn, id=createRoleForm, id=createRoleFormElement

// 编辑角色弹窗
window.editRole = function(roleId) {
  fetch(`/api/admin/roles`, {
    headers: {
      'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
    }
  })
    .then(res => res.json())
    .then(data => {
      if (data.success && Array.isArray(data.data)) {
        const role = data.data.find(r => r.id === roleId);
        if (!role) return alert('角色不存在');
        
        // 填充基本信息表单
        document.getElementById('roleName').value = role.name;
        document.getElementById('roleDesc').value = role.description || '';
        document.getElementById('editRoleId').value = role.id;
        document.getElementById('modalTitle').textContent = '编辑角色 - ' + role.name;
        
        // 显示权限分配界面
        document.getElementById('createRoleForm').style.display = 'block';
        document.getElementById('permissionAssignment').style.display = 'block';
        
        // 加载角色权限数据
        loadRolePermissions(roleId);
      }
    });
};

// 删除角色
window.deleteRole = function(roleId) {
  if (!confirm('确定要删除该角色吗？')) return;
  fetch(`/api/admin/roles/${roleId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
    }
  })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert('删除成功');
        loadRoleList();
      } else {
        alert(data.message || '删除失败');
      }
    });
};

// 查看角色日志
window.viewRoleLog = function(roleId) {
  const token = localStorage.getItem('access_token') || '';
  if (!token) {
    if (window.Swal) {
      Swal.fire('提示', '未检测到登录凭证，请重新登录后再试。', 'warning');
    } else {
      alert('未检测到登录凭证，请重新登录后再试。');
    }
    return;
  }
  
  // 使用统一日志系统查询角色操作日志
  fetch(`/api/admin/logs?target_id=${roleId}&action=UPDATE,CREATE,DELETE`, {
    headers: {
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    }
  })
    .then((response) => {
      if (response.status === 401) throw new Error('未认证或Token无效');
      return response.json();
    })
    .then((data) => {
      if (data.success && data.data && data.data.length > 0) {
        // Format logs for display
        let html = data.data
          .map((log) => {
            let localTime = log.operation_time
              ? new Date(log.operation_time).toLocaleString()
              : "";
            let restoreButton = "";

            // 根据日志类型显示不同的恢复按钮
            const actionLower = log.action.toLowerCase();
            if (actionLower === "delete") {
              restoreButton = `<button class="btn btn-sm btn-outline-success mt-2" onclick="restoreRoleLog(${log.id})">恢复已删除角色</button>`;
            } else if (actionLower === "restore") {
              restoreButton = `<span class="badge bg-info mt-2">恢复操作记录</span>`;
            } else if (
              log.old_content &&
              (actionLower === "create" || actionLower === "update")
            ) {
              restoreButton = `<button class="btn btn-sm btn-outline-primary mt-2" onclick="restoreRoleLog(${log.id})">恢复此版本</button>`;
            }

            return `<div style="border-bottom:1px solid #eee;margin-bottom:12px;padding-bottom:8px;">
              <div><strong>操作类型：</strong>${log.action} | <strong>操作人：</strong>${log.operator || '系统'} | <strong>时间：</strong>${localTime}</div>
              ${log.new_content ? `<div><strong>当前内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#e8f5e8;padding:8px;border-radius:4px;border-left:4px solid #28a745;">${log.new_content}</pre></div>` : ""}
              ${log.old_content ? `<div><strong>历史内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#fff3cd;padding:8px;border-radius:4px;border-left:4px solid #ffc107;">${log.old_content}</pre>${restoreButton ? `<div style="margin-top:8px;">${restoreButton}</div>` : ""}</div>` : ""}
            </div>`;
          })
          .join("");

        if (window.Swal) {
          Swal.fire({
            title: '角色操作日志',
            html: `<div style="max-height:600px;overflow-y:auto;text-align:left;">${html}</div>`,
            width: 1000,
            showConfirmButton: false,
            showCloseButton: true,
          });
        } else {
          alert("日志功能需要引入 SweetAlert2 支持美观弹窗。");
        }
      } else {
        if (window.Swal) {
          Swal.fire("无日志", "该角色暂无操作日志", "info");
        } else {
          alert("该角色暂无操作日志");
        }
      }
    })
    .catch((error) => {
      if (window.Swal) {
        Swal.fire("获取日志失败", "网络错误：" + error.message, "error");
      } else {
        alert("获取角色日志失败: " + error.message);
      }
    });
};

document.addEventListener('DOMContentLoaded', function () {
  loadRoleList();
  const createRoleBtn = document.getElementById('createRoleBtn');
  const createRoleForm = document.getElementById('createRoleForm');
  const createRoleFormElement = document.getElementById('createRoleFormElement');

  // 打开创建角色弹窗
  if (createRoleBtn && createRoleForm) {
    createRoleBtn.addEventListener('click', function () {
      createRoleForm.style.display = 'block';
    });
  }

  // 关闭弹窗（点击遮罩或ESC等可后续补全）
  if (createRoleForm) {
    createRoleForm.addEventListener('click', function (e) {
      if (e.target === createRoleForm) {
        createRoleForm.style.display = 'none';
      }
    });
  }

  // 创建角色表单提交
  if (createRoleFormElement) {
    createRoleFormElement.onsubmit = function (e) {
      e.preventDefault();
      const roleName = document.getElementById('roleName').value.trim();
      const roleDesc = document.getElementById('roleDesc').value.trim();
      const editRoleId = document.getElementById('editRoleId').value;
      
      if (!roleName) {
        alert('角色名不能为空');
        return;
      }
      
      let url = '/api/admin/roles';
      let method = 'POST';
      let body = { name: roleName, description: roleDesc };
      
      if (editRoleId) {
        url = `/api/admin/roles/${editRoleId}`;
        method = 'PUT';
      }
      
      // 保存角色基本信息
      fetch(url, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
        },
        body: JSON.stringify(body)
      })
        .then(res => res.json().then(data => ({ status: res.status, data })))
        .then(({ status, data }) => {
          if (data.success) {
            const roleId = editRoleId || data.data.id;
            
            // 如果是编辑模式且权限分配界面可见，保存权限分配
            if (editRoleId && document.getElementById('permissionAssignment').style.display === 'block') {
              const selectedPermissions = Array.from(document.querySelectorAll('.permission-checkbox:checked'))
                .map(cb => parseInt(cb.dataset.permissionId));
              
              updateRolePermissions(roleId, selectedPermissions)
                .then(permData => {
                  if (permData.success) {
                    alert('角色信息和权限保存成功');
                  } else {
                    alert('角色信息保存成功，但权限保存失败: ' + permData.message);
                  }
                  closeRoleModal();
                  loadRoleList();
                })
                .catch(err => {
                  alert('角色信息保存成功，但权限保存失败: ' + err.message);
                  closeRoleModal();
                  loadRoleList();
                });
            } else {
              alert(editRoleId ? '角色修改成功' : '角色创建成功');
              closeRoleModal();
              loadRoleList();
            }
          } else {
            alert(data.message || data.msg || '操作失败');
          }
        })
        .catch(err => {
          alert('请求失败: ' + err);
        });
    };
  }
});

// 恢复角色日志
window.restoreRoleLog = function(logId) {
    const token = localStorage.getItem('access_token') || '';
    if (!token) {
        if (window.Swal) {
            Swal.fire('提示', '未检测到登录凭证，请重新登录后再试。', 'warning');
        } else {
            alert('未检测到登录凭证，请重新登录后再试。');
        }
        return;
    }
    
    if (window.Swal) {
        Swal.fire({
            title: '确认恢复',
            text: '确定要恢复此版本的角色信息吗？',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '确定恢复',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                performRoleRestore(logId, token);
            }
        });
    } else {
        if (confirm('确定要恢复此版本的角色信息吗？')) {
            performRoleRestore(logId, token);
        }
    }
};

// 执行角色恢复操作
function performRoleRestore(logId, token) {
    fetch(`/api/admin/logs/${logId}/restore`, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (window.Swal) {
                Swal.fire('恢复成功', '角色信息已恢复到指定版本', 'success');
            } else {
                alert('恢复成功');
            }
            // 重新加载角色列表
            loadRoleList();
        } else {
            if (window.Swal) {
                Swal.fire('恢复失败', data.message || '恢复操作失败', 'error');
            } else {
                alert('恢复失败: ' + (data.message || '恢复操作失败'));
            }
        }
    })
    .catch(error => {
        if (window.Swal) {
            Swal.fire('恢复失败', '网络错误：' + error.message, 'error');
        } else {
            alert('恢复失败: ' + error.message);
        }
    });
}


// ========== 权限分配功能 (按照附件13第10.1.1节要求实现) ==========

/**
 * 加载角色权限 - 调用API获取角色当前权限
 * @param {number} roleId 角色ID
 */
function loadRolePermissions(roleId) {
    fetch(`/api/admin/roles/${roleId}/permissions`, {
        headers: {
            'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderPermissionCheckboxes(data.data.permission_groups, data.data.role);
            updatePermissionSummary();
        } else {
            console.error('加载角色权限失败:', data.message);
            alert('加载权限失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('加载角色权限失败:', error);
        alert('加载权限失败');
    });
}

/**
 * 渲染权限选择界面 - 按类别分组显示权限
 * @param {Array} permissionGroups 权限分组数据
 * @param {Object} role 角色信息
 */
function renderPermissionCheckboxes(permissionGroups, role) {
    const container = document.getElementById('permissionGroups');
    container.innerHTML = '';
    
    // 权限类别中文名映射
    const categoryNames = {
        user: '用户管理',
        student: '学生档案',
        vision: '视力数据',
        intervention: '干预记录',
        followup: '随访管理',
        report: '报告管理',
        miniprogram: '微信小程序',
        social: '社交功能',
        feedback: '反馈管理',
        system: '系统管理',
        role: '角色管理',
        permission: '权限管理',
        log: '日志管理',
        data: '数据权限',
        audit: '审核权限'
    };
    
    permissionGroups.forEach(group => {
        const categoryName = categoryNames[group.category] || group.category;
        const assignedCount = group.permissions.filter(p => p.assigned).length;
        
        const groupDiv = document.createElement('div');
        groupDiv.className = 'permission-group';
        groupDiv.innerHTML = `
            <div class="permission-group-header" onclick="togglePermissionGroup('${group.category}')">
                ${categoryName} (${assignedCount}/${group.permissions.length})
                <span class="float-end">
                    <i class="fas fa-chevron-down" id="icon-${group.category}"></i>
                </span>
            </div>
            <div class="permission-group-content" id="content-${group.category}" style="display: none;">
                ${group.permissions.map(permission => `
                    <div class="permission-item">
                        <div class="permission-info">
                            <div class="permission-code">${permission.code}</div>
                            <div class="permission-name">${permission.name}</div>
                            <div class="permission-description">${permission.description || ''}</div>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input permission-checkbox" 
                                   type="checkbox" 
                                   id="perm-${permission.id}"
                                   data-permission-id="${permission.id}"
                                   data-permission-code="${permission.code}"
                                   ${permission.assigned ? 'checked' : ''}
                                   onchange="updatePermissionSummary()">
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
        container.appendChild(groupDiv);
    });
}

/**
 * 切换权限分组的展开/折叠状态
 * @param {string} category 权限类别
 */
function togglePermissionGroup(category) {
    const content = document.getElementById(`content-${category}`);
    const icon = document.getElementById(`icon-${category}`);
    
    if (content.style.display === 'none') {
        content.style.display = 'block';
        icon.className = 'fas fa-chevron-up';
    } else {
        content.style.display = 'none';
        icon.className = 'fas fa-chevron-down';
    }
}

/**
 * 更新权限分配摘要信息
 */
function updatePermissionSummary() {
    const checkboxes = document.querySelectorAll('.permission-checkbox');
    const checkedCount = document.querySelectorAll('.permission-checkbox:checked').length;
    const totalCount = checkboxes.length;
    
    document.getElementById('permissionSummary').textContent = 
        `已选择 ${checkedCount} / ${totalCount} 个权限`;
}

/**
 * 全选/取消全选权限
 */
function toggleAllPermissions() {
    const checkboxes = document.querySelectorAll('.permission-checkbox');
    const allChecked = Array.from(checkboxes).every(cb => cb.checked);
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = !allChecked;
    });
    
    updatePermissionSummary();
}

/**
 * 更新角色权限 - 调用API保存权限分配
 * @param {number} roleId 角色ID
 * @param {Array} permissionIds 权限ID数组
 * @returns {Promise}
 */
function updateRolePermissions(roleId, permissionIds) {
    return fetch(`/api/admin/roles/${roleId}/permissions`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
        },
        body: JSON.stringify({
            permission_ids: permissionIds
        })
    })
    .then(response => response.json());
}

/**
 * 关闭角色编辑模态框
 */
function closeRoleModal() {
    document.getElementById('createRoleForm').style.display = 'none';
    document.getElementById('permissionAssignment').style.display = 'none';
    document.getElementById('createRoleFormElement').reset();
    document.getElementById('editRoleId').value = '';
    document.getElementById('modalTitle').textContent = '创建新角色';
}

// 将函数暴露到全局作用域
window.loadRolePermissions = loadRolePermissions;
window.updateRolePermissions = updateRolePermissions;
window.togglePermissionGroup = togglePermissionGroup;
window.toggleAllPermissions = toggleAllPermissions;
window.closeRoleModal = closeRoleModal;
